package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.bean.ScoreDetailResponse;
import com.ycsj.goldmedalnewconcept.bean.ScoreDetailResponse.ScoreDetail;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.R;

//成绩查询
@SuppressLint("HandlerLeak")
public class ScoreQueryActivity extends Activity implements OnRefreshListener,
		OnClickListener {
	private ListView lv_friends;
	private ScoreQueryAdapter mAdapter;
	private ImageView iv_back;
	private PullToRefreshLayout refreshLayout;
	private List<ScoreDetail> list;
	private List<ScoreDetail> list2;
	private String role;
	private String account;
	private String rowid;
	private int page = 0;
	private TextView loadTextView;
	private TextView tv_empty;
	private View footerView;
	private View loading;
	private boolean isLoading = false;
	private RotateAnimation loadingAnimation;
	private List<String> imglist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_scorequery);

		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");

		list = new ArrayList<ScoreDetail>();
		list2 = new ArrayList<ScoreDetail>();

		loadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(this,
				R.anim.rotating);
		// 添加匀速转动动画
		LinearInterpolator lir = new LinearInterpolator();
		loadingAnimation.setInterpolator(lir);

		initView();
		setOnListener();
		initData();
	}

	private void initView() {

		lv_friends = (ListView) findViewById(R.id.lv_friends);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		refreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);

		footerView = this.getLayoutInflater().inflate(R.layout.load_more_jpstar, null);
		loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
		lv_friends.addFooterView(footerView, null, false);
		footerView.setOnClickListener(this);

	}

	private void setOnListener() {
		refreshLayout.setOnRefreshListener(this);

		iv_back.setOnClickListener(this);
	}

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "40");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("page", page + "");
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=40&c=18271261779&role=1&page=0
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				ScoreDetailResponse fromJson = gson.fromJson(json,
						ScoreDetailResponse.class);

				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							|| "0".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								if (page == 0) {
									tv_empty.setVisibility(tv_empty.VISIBLE);
								}

								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								loadTextView.setText("已经是最后一条了");
								loadTextView.setClickable(false);
								isLoading = true;
								page = 0;
							}
						});
					} else if ("1".equals(fromJson.state)) {
						list2 = fromJson.list;
						if (page == 0) {
							list = list2;
						} else {
							list.addAll(list2);
						}
						runOnUiThread(new Runnable() {
							@Override
							public void run() {

								refreshLayout
										.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
								mAdapter = new ScoreQueryAdapter();
								if (page == 0) {

									lv_friends.setAdapter(mAdapter);

								} else {
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											mAdapter.notifyDataSetChanged();
										}
									});
								}

								lv_friends
										.setOnItemClickListener(new OnItemClickListener() {

											@Override
											public void onItemClick(
													AdapterView<?> parent,
													View view, int position,
													long id) {
												Intent intent = new Intent(
														ScoreQueryActivity.this,
														ScoreQueryDetailActivity.class);
												intent.putExtra(
														"content",
														list.get(position).content);
												intent.putExtra(
														"score",
														list.get(position).score);
												if (list.get(position).picture1 != null
														&& !"".equals(list
																.get(position).picture1)) {
													intent.putExtra(
															"pic1",
															list.get(position).picture1);
												}
												if (list.get(position).picture2 != null
														&& !"".equals(list
																.get(position).picture2)) {
													intent.putExtra(
															"pic2",
															list.get(position).picture2);
												}
												if (list.get(position).picture3 != null
														&& !"".equals(list
																.get(position).picture3)) {
													intent.putExtra(
															"pic3",
															list.get(position).picture3);
												}
												if (list.get(position).picture4 != null
														&& !"".equals(list
																.get(position).picture4)) {
													intent.putExtra(
															"pic4",
															list.get(position).picture4);
												}
												if (list.get(position).picture5 != null
														&& !"".equals(list
																.get(position).picture5)) {
													intent.putExtra(
															"pic5",
															list.get(position).picture5);
												}
												if (list.get(position).picture6 != null
														&& !"".equals(list
																.get(position).picture6)) {
													intent.putExtra(
															"pic6",
															list.get(position).picture6);
												}
												if (list.get(position).picture7 != null
														&& !"".equals(list
																.get(position).picture7)) {
													intent.putExtra(
															"pic7",
															list.get(position).picture7);
												}
												if (list.get(position).picture8 != null
														&& !"".equals(list
																.get(position).picture8)) {
													intent.putExtra(
															"pic8",
															list.get(position).picture8);
												}
												if (list.get(position).picture9 != null
														&& !"".equals(list
																.get(position).picture9)) {
													intent.putExtra(
															"pic9",
															list.get(position).picture9);
												}

												startActivity(intent);
											}
										});

								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								if (list2.size() < 10) {
									loadTextView.setText("已经是最后一条了");
									loadTextView.setClickable(false);
									isLoading = true;
									page = 0;
								} else {
									loadTextView.setText("加载更多");
									isLoading = false;
								}
							}
						});
					}
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.loadmore_layout:
			if (!isLoading) {
				loading.setVisibility(View.VISIBLE);
				loading.startAnimation(loadingAnimation);
				loadTextView.setText("正在加载...");
				isLoading = true;
				page++;
				initData();
			}
			break;
		}
	}

	class ScoreQueryAdapter extends BaseAdapter {

		public int getCount() {

			return list.size();
		}

		public Object getItem(int position) {

			return null;
		}

		public long getItemId(int position) {

			return 0;
		}

		ViewHolder vh = null;

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(parent.getContext(),
						R.layout.item_scorequery, null);
				vh = new ViewHolder();

				vh.ll_imgs = (LinearLayout) convertView
						.findViewById(R.id.ll_imgs);
				vh.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
				vh.iv_img1 = (ImageView) convertView.findViewById(R.id.iv_img1);
				vh.iv_img2 = (ImageView) convertView.findViewById(R.id.iv_img2);
				vh.iv_img3 = (ImageView) convertView.findViewById(R.id.iv_img3);
				vh.tv_title = (TextView) convertView
						.findViewById(R.id.tv_title);
				vh.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
				vh.tv_content = (TextView) convertView
						.findViewById(R.id.tv_content);
				vh.iv_img.setVisibility(vh.iv_img.GONE);
				vh.ll_imgs.setVisibility(vh.ll_imgs.GONE);
				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}
			imglist = new ArrayList<String>();
			if (list != null) {
				if (list.get(position).picture1 != null
						&& !"".equals(list.get(position).picture1)) {
					imglist.add(list.get(position).picture1);
				}
				if (list.get(position).picture2 != null
						&& !"".equals(list.get(position).picture2)) {
					imglist.add(list.get(position).picture2);
				}
				if (list.get(position).picture3 != null
						&& !"".equals(list.get(position).picture3)) {
					imglist.add(list.get(position).picture3);
				}
			}

			if (imglist.size() == 0) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.GONE);
				vh.iv_img.setVisibility(vh.iv_img.GONE);
			} else if (imglist.size() == 1) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.GONE);
				vh.iv_img.setVisibility(vh.iv_img.VISIBLE);
				Picasso.with(ScoreQueryActivity.this)
						.load(list.get(position).picture1).into(vh.iv_img);
			} else if (imglist.size() == 2) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.VISIBLE);
				vh.iv_img.setVisibility(vh.iv_img.GONE);

				Picasso.with(ScoreQueryActivity.this)
						.load(list.get(position).picture1).into(vh.iv_img1);

				Picasso.with(ScoreQueryActivity.this)
						.load(list.get(position).picture2).into(vh.iv_img2);
			} else if (imglist.size() == 3) {
				vh.ll_imgs.setVisibility(vh.ll_imgs.VISIBLE);
				vh.iv_img.setVisibility(vh.iv_img.GONE);

				Picasso.with(ScoreQueryActivity.this)
						.load(list.get(position).picture1).into(vh.iv_img1);

				Picasso.with(ScoreQueryActivity.this)
						.load(list.get(position).picture2).into(vh.iv_img2);

				Picasso.with(ScoreQueryActivity.this)
						.load(list.get(position).picture3).into(vh.iv_img3);

			}

			vh.tv_title.setText(list.get(position).tag);
			vh.tv_time.setText(list.get(position).update_date);
			vh.tv_content.setText(list.get(position).content);

			return convertView;
		}

		class ViewHolder {
			private TextView tv_title;
			private ImageView iv_img;
			private ImageView iv_img1;
			private ImageView iv_img2;
			private ImageView iv_img3;
			private TextView tv_time;
			private TextView tv_content;
			private LinearLayout ll_imgs;

		}
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		if (!"1".equals(role)) {
			onRefresh();
		}
	}

	@Override
	public void onRefresh() {
		// 下拉刷新操作
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				page = 0;
				initData();
				loadTextView.setText("加载更多");
				loading.setVisibility(View.GONE);
				isLoading = false;

			}
		}, 500);
	}

}
